<template>
	<view class="container">
		<!-- 顶部文本 -->
		<view class="header">
			<text class="header-text">{{name}}</text>
		</view>
		<!-- 设备列表 -->
		<scroll-view class="device-list" scroll-y>
			<view v-for="(device, index) in deviceList" :key="index" class="device-item"
				:class="{ selected: selectedDevice.deviceId === device.deviceId }" @click="connetConfirm(device)">
				<view class="device-info">
					<text class="device-name">{{ device.name }}</text>
					<text class="mac-address">{{ device.deviceId }}</text>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-if="deviceList.length === 0" class="empty-state">
				<image src="#" class="empty-icon" />
				<text class="empty-text">未发现蓝牙设备</text>
			</view>
		</scroll-view>

		<!-- 操作按钮 -->
		<view class="action-buttons">
			<button class="connect-btn" :style="{ background: selectedDevice ? '#44CF8E' : '#E0E0E0' }"
				@click="initBlue">
				初始化
			</button>

			<button class="connect-btn" :style="{ background: selectedDevice ? '#44CF8E' : '#E0E0E0' }"
				@click="connetBlue">
				连接设备
			</button>

			<button class="disconnect-btn" :style="{ background: isLink ? '#FF4444' : '#E0E0E0' }"
				@click="handleDisconnect">
				断开连接
			</button>

			<button v-if="isLink" :style="{ background: selectedDevice ? '#44CF8E' : '#E0E0E0' }" class="connect-btn"
				@click="gotoIndex">
				打开蓝牙调试
			</button>
		</view>
	</view>
</template>

<script>
	import {
		hexUtils
	} from "@/common/utils";

	export default {
		data() {
			return {
				deviceList: [],
				selectedDevice: {
					deviceId: null
				},
				name: undefined,
				isLink: false,
				showList: false,
				searchVal: '可用设备',
				device: {
					deviceId: "--",
					name: "--",
				},
				uuid: {
					deviceId: '',
					serviceId: '',
					writeId: '',
					notifyId: ''
				},
				discovering: '',
				keyWord: '',
				searchlist: [], // 模糊查询匹配
			}
		},
		onLoad() {
			//监听蓝牙连接状态
			uni.onBLEConnectionStateChange(res => {
				console.log(`设备${res.deviceId},连接:${res.connected}`)
				if (res.connected === false) {
					this.clearData()
				}
			})
		},
		mounted() {
			let that = this
			that.searchVal = that.device.name != '--' ? that.device.name : '可用设备'
			that.initBlue()
		},
		methods: {
			// 清空数据
			clearData() {
				let that = this
				that.device = {
					deviceId: "--",
					name: "--",
				}
				that.uuid = null;
				that.searchVal = '可用设备';
			},

			handleDisconnect() {
				this.isLink = false
				this.selectedDevice = null
				uni.showToast({
					title: '已断开连接',
					icon: 'none'
				})
			},
			gotoIndex() {
				uni.navigateTo({
					url: `/pages/index/bluetooth`
				});
			},
			// 打开蓝牙适配器
			initBlue() {
				let that = this;
				that.showList = true
				uni.openBluetoothAdapter({
					success(res) {
						console.log('打开蓝牙适配器成功');
						that.findBlue()
					},
					fail() {
						console.log('打开蓝牙适配器失败');
						uni.showToast({
							title: '请打开蓝牙',
							type: 'error',
							icon: 'none'
						})
					}
				})
			},


			// 搜索周边设备
			findBlue() {
				let that = this
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: false,
					interval: 0,
					success(res) {
						console.log('设备搜索中');
						uni.onBluetoothDeviceFound(devices => {
							that.getBlue()
						})
					},
					fail() {
						console.log('设备搜索失败');
						uni.showToast({
							icon: 'none',
							title: '无法获取'
						})
					}
				})
			},

			// 获取搜索到的设备信息
			getBlue() {
				let that = this
				that.listShow = !that.listShow

        let devices = [];
        let canUsedDevices  = [];

				uni.getBluetoothDevices({
          success(res) {
            devices = res.devices;
            for (let i = 0; i < devices.length; i++) {
              let hex = Array.prototype.map.call(new Uint8Array(devices[i].advertisData), x => (
                  '00' + x.toString(16)).slice(-2)).join('');
              let str = hex.slice(0, 4);
              if (str == '7816') { // 根据厂商型号确认蓝牙类别
                console.log('【袁总】蓝牙设备广播：', hex)
                let deviceMac = hex.slice(4, 16); // 获取到真实的Mac
                devices[i].deviceMac = convertToMacAddress(deviceMac);
                devices[i].deviceSupplier = "yuan"; // 供应商
                devices[i].deviceName = devices[i].name;
                canUsedDevices.push(devices[i]);
              }

              if (str == '6816') { // 根据厂商型号确认蓝牙类别
                console.log('【周总】蓝牙设备广播：', hex)
                let deviceMac = hex.slice(4, 16); // 获取到真实的Mac
                devices[i].deviceMac = convertToMacAddress(deviceMac);
                devices[i].deviceSupplier = "zhou"; // 供应商
                devices[i].deviceName = devices[i].name;
                canUsedDevices.push(devices[i]);
              }
            }

            /**
             * 将真实Mac地址转换出来
             * @param str
             * @returns {string}
             */
            function convertToMacAddress(str) {
              return str.replace(/(.{2})/g, '$1:').slice(0, -1).toUpperCase();
            }

            that.deviceList = filterArrObj(canUsedDevices, 'deviceId');

            // 过滤重复蓝牙数据数据
            function filterArrObj(arr, filterField) {
              let newArr = arr.reduce((pre, cur) =>
                  (pre.some(item => item[filterField] == cur[filterField]) ? pre : [...pre,
                    cur
                  ]), []);
              return newArr;
            }
          },

					fail() {
						uni.showToast({
							icon: 'none',
							title: '无法获取'
						})
					}
				})

				console.log('deviceList:', that.deviceList)
			},
			// 选中设备
			connetConfirm(device) {
				this.name = device.name
				this.selectedDevice = device;
				getApp().globalData.bluetooth.deviceName = device.name
				this.keyWord = device.name
				this.deviceInfo = device
			},

			// 连接选中设备
			connetBlue() {
				let that = this;
				if (!that.deviceInfo) {
					uni.showToast({
						title: '请选择设备',
						icon: 'none',
					})
					return
				}
				let deviceId = that.deviceInfo.deviceId;

				console.log('deviceId', deviceId);
				uni.createBLEConnection({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: deviceId, //设备id
					success(res) {
						console.log("连接蓝牙成功", res)
						uni.showToast({
							title: '连接中',
							icon: 'loading',
							duration: 2000
						})
						that.showList = false
						uni.stopBluetoothDevicesDiscovery({
							success(res) {
								// console.log('连接蓝牙成功之后关闭蓝牙搜索');
							}
						})
						that.getServiceId(that.deviceInfo)
					},
					fail() {
						// console.log("连接蓝牙失败!-->11111")
						uni.showToast({
							icon: 'none',
							title: `错误`
						})
					}
				})
			},

			// 获取蓝牙设备服务
			getServiceId(item) {
				let deviceId = item.deviceId
				let that = this
				setTimeout(() => {
					uni.getBLEDeviceServices({
						deviceId: deviceId,
						success(res) {
							if (res.services.length == 0) {
								uni.showToast({
									icon: 'none',
									title: '设备不可用',
									duration: 1000
								})
								that.cancelConcent()
							} else {
								that.uuid.deviceId = deviceId
								that.uuid.serviceId = res.services[2].uuid //根据实际情况选择
								that.getCharacteId(that.uuid)
							}
						},
						fail() {
							uni.showToast({
								icon: 'none',
								title: '获取服务失败'
							})
						}
					})
				}, 1000)
			},

			// 获取蓝牙特征值
			getCharacteId(item) {
				let that = this
				uni.getBLEDeviceCharacteristics({
					deviceId: item.deviceId,
					serviceId: item.serviceId,
					success(res) {
						// console.log('获取蓝牙特征值', res)
						for (let i = 0; i < res.characteristics.length; i++) {
							let model = res.characteristics[i]
							if (model.properties.write) {
								that.uuid.writeId = model.uuid;
							}
							if (model.properties.notify) {
								//model.uuid:用来notify的uuid值
								that.uuid.notifyId = model.uuid
							}
						}
						that.uuid.deviceId = item.deviceId;
						that.startNotice(that.uuid)
					},
					fail() {
						uni.showToast({
							icon: 'none',
							title: '获取特征值失败'
						})
					}
				})
			},

			// 启用 notify 功能
			startNotice(e) {
				let that = this
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					deviceId: e.deviceId,
					serviceId: e.serviceId,
					characteristicId: e.notifyId,
					success(res) {
						console.log('启用 notify 功能', res);
						onChange()
					},
					fail() {
						// console.log('启用 notify 功能失败')
					}
				})


				function onChange() {
					let isCommit = true
					console.log("开始调用监听方法...")
					uni.onBLECharacteristicValueChange(function(characteristic) {
						let deviceId = characteristic.deviceId;

						let hex = Array.prototype.map.call(new Uint8Array(characteristic.value), x => ('00' + x
							.toString(16)).slice(-2)).join('');
						// console.log("hex", hex, '长度：', hex.length);
						let version = hex.length
						if (version === 8) {

							let hexData = hex.substring(0, 4);
							let data = hexUtils.convertHexTo10(hexData);
							let khwHex = hex.substring(4, 8);
							let voltage = hexUtils.convertHexTo10(khwHex);
							voltage = hexUtils.calPercentage(voltage);

              console.log("数据：", data, '电压：', voltage)


							getApp().globalData.bluetooth.deviceId = deviceId;
							getApp().globalData.bluetooth.deviceMac = that.deviceInfo.deviceMac;
							getApp().globalData.bluetooth.deviceVersion = '4.0'
							getApp().globalData.bluetooth.deviceCategory = 'one'
							getApp().globalData.bluetooth.deviceSupplier = that.deviceInfo.deviceSupplier
							getApp().globalData.bluetooth.voltage = voltage;
							getApp().globalData.bluetooth.isLink = true;

							if (isCommit) {
								that.isLink = true
								isCommit = false
							}
						}
					});
				}
			},

			// 断开连接
			cancelConcent(e) {
				let that = this
				if (that.device.deviceId !== '--') {
					uni.closeBLEConnection({
						deviceId: that.deviceId,
						success(res) {
							console.log(' 断开连接成功', res)
						},
						fail(err) {
							console.log(' 断开连接失败', err)
						},
					})
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	$primary-green: #44CF8E;
	$border-color: #E0E0E0;

	.container {
		background: #F8F8F8;
		padding: 32rpx;
	}

	.header {
		padding: 32rpx 0;
		border-bottom: 1px solid $border-color;

		&-text {
			font-size: 36rpx;
			color: #333;
			font-weight: 500;
		}
	}

	.device-list {
		height: 65vh;
		margin: 24rpx 0;
		background: white;
		border-radius: 16rpx;

		.device-item {
			padding: 32rpx;
			border-bottom: 1px solid $border-color;
			transition: all 0.2s;

			&.selected {
				border-left: 8rpx solid $primary-green;
				background: rgba($primary-green, 0.05);
			}

			.device-info {
				display: flex;
				flex-direction: column;
				gap: 8rpx;

				.device-name {
					font-size: 32rpx;
					color: #333;
				}

				.mac-address {
					font-size: 26rpx;
					color: #666;
					font-family: monospace;
				}
			}

			&:last-child {
				border-bottom: none;
			}
		}

		.empty-state {
			padding: 120rpx 0;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			text-align: center;

			.empty-icon {
				width: 160rpx;
				height: 160rpx;
				opacity: 0.3;
			}

			.empty-text {
				margin-top: 24rpx;
				color: #999;
				font-size: 28rpx;
			}
		}
	}

	.action-buttons {
		button {
			height: 96rpx;
			border-radius: 48rpx;
			font-size: 32rpx;
			color: white;
			transition: all 0.2s;

			&::after {
				border: none;
			}

			&.connect-btn {
				margin-bottom: 24rpx;
			}
		}
	}
</style>
